"""
病历相关的 Pydantic 模型
遵循 FastAPI 标准流程：
- 请求模型（Create, Update, Query）
- 响应模型（Response, Brief, Paginated）
"""
from pydantic import BaseModel, Field, field_validator
from typing import Optional, List
from datetime import datetime


# ========== 基础模型 ==========
class MedicalRecordBase(BaseModel):
    """病历基础字段"""
    patient_id: int = Field(..., alias="patient_id", description="患者ID")
    patient_name: Optional[str] = Field(None, alias="patientName", max_length=100, description="患者姓名")
    
    # 诊断信息
    initial_diagnosis: List[str] = Field(..., alias="initialDiagnosis", description="初步诊断")
    onset_date: Optional[datetime] = Field(None, alias="onsetDate", description="发病日期")
    course_days: Optional[int] = Field(None, alias="courseDays", ge=0, description="病程(天)")
    
    # 评分信息
    nihss_score: Optional[int] = Field(None, alias="nihssScore", ge=0, le=42, description="NIHSS评分")
    
    # 病灶信息
    stroke_location: Optional[str] = Field(None, alias="strokeLocation", description="梗塞部位")
    paralysis_location: Optional[str] = Field(None, alias="paralysisLocation", description="偏瘫部位")
    
    # 手术信息
    has_surgery: Optional[bool] = Field(None, alias="hasSurgery", description="是否手术")
    surgery_types: Optional[List[str]] = Field(None, alias="surgeryTypes", description="手术类型")
    
    # 动脉狭窄
    has_artery_stenosis: Optional[bool] = Field(None, alias="hasArteryStenosis", description="有动脉狭窄")
    artery_types: Optional[List[str]] = Field(None, alias="arteryTypes", description="动脉狭窄类型")
    neck_vessel_ultrasound: Optional[str] = Field(None, alias="neckVesselUltrasound", description="颈部血管超声")
    
    # 语言功能
    has_language_disorder: Optional[bool] = Field(None, alias="languageDisorder", description="有语言功能障碍")
    disorder_type: Optional[str] = Field(None, alias="disorderType", description="障碍类型")
    
    class Config:
        populate_by_name = True  # 允许使用字段名或别名


# ========== 创建病历 ==========
class MedicalRecordCreate(MedicalRecordBase):
    """创建病历时的输入"""
    
    class Config:
        json_schema_extra = {
            "example": {
            "patient_id": 1,
            "patient_name": "张三",
            "initial_diagnosis": ["脑梗塞", "高血压"],
            "onset_date": "2024-11-01T08:00:00",
            "course_days": 3,
            "nihss_score": 8,
            "stroke_location": "左侧大脑中动脉供血区",
            "paralysis_location": "右侧肢体",
            "has_surgery": True,
            "surgery_types": ["血管内治疗", "去骨瓣减压术"],
            "has_artery_stenosis": True,
            "artery_types": ["颈内动脉狭窄", "大脑中动脉狭窄"],
            "neck_vessel_ultrasound": "颈动脉粥样硬化斑块形成",
            "has_language_disorder": True,
            "disorder_type": "运动性失语"
            }
        }


# ========== 更新病历 ==========
class MedicalRecordUpdate(BaseModel):
    """更新病历信息（所有字段可选）"""
    patient_name: Optional[str] = Field(None, alias="patientName", max_length=100)
    initial_diagnosis: Optional[List[str]] = Field(None, alias="initialDiagnosis")
    onset_date: Optional[datetime] = Field(None, alias="onsetDate")
    course_days: Optional[int] = Field(None, alias="courseDays", ge=0)
    nihss_score: Optional[int] = Field(None, alias="nihssScore", ge=0, le=42)
    stroke_location: Optional[str] = Field(None, alias="strokeLocation")
    paralysis_location: Optional[str] = Field(None, alias="paralysisLocation")
    has_surgery: Optional[bool] = Field(None, alias="hasSurgery")
    surgery_types: Optional[List[str]] = Field(None, alias="surgeryTypes")
    has_artery_stenosis: Optional[bool] = Field(None, alias="hasArteryStenosis")
    artery_types: Optional[List[str]] = Field(None, alias="arteryTypes")
    neck_vessel_ultrasound: Optional[str] = Field(None, alias="neckVesselUltrasound")
    has_language_disorder: Optional[bool] = Field(None, alias="languageDisorder")
    disorder_type: Optional[str] = Field(None, alias="disorderType")
    
    class Config:
        populate_by_name = True  # 允许使用字段名或别名


# ========== 病历响应 ==========
class MedicalRecordResponse(MedicalRecordBase):
    """API返回的病历数据"""
    id: int
    status: int
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True
    
    def to_flask_format(self) -> dict:
        """转换为原 Flask 项目的响应格式"""
        return {
            "_id": str(self.id),
            "patient_id": str(self.patient_id),
            "patientName": self.patient_name,
            "initialDiagnosis": self.initial_diagnosis,
            "onsetDate": self.onset_date.isoformat() if self.onset_date else None,
            "courseDays": self.course_days,
            "nihssScore": self.nihss_score,
            "strokeLocation": self.stroke_location,
            "paralysisLocation": self.paralysis_location,
            "hasSurgery": self.has_surgery,
            "surgeryTypes": self.surgery_types,
            "hasArteryStenosis": self.has_artery_stenosis,
            "arteryTypes": self.artery_types,
            "neckVesselUltrasound": self.neck_vessel_ultrasound,
            "languageDisorder": self.has_language_disorder,
            "disorderType": self.disorder_type,
            "status": self.status,
            "createdAt": self.created_at.isoformat() if self.created_at else None,
            "updatedAt": self.updated_at.isoformat() if self.updated_at else None
        }


# ========== 病历简要信息 ==========
class MedicalRecordBrief(BaseModel):
    """病历简要信息（用于列表展示）"""
    id: int
    patient_id: int
    patient_name: Optional[str]
    initial_diagnosis: List[str]
    onset_date: Optional[datetime]
    nihss_score: Optional[int]
    status: int
    created_at: datetime
    
    class Config:
        from_attributes = True


# ========== 查询参数 Schema ==========
class MedicalRecordQueryParams(BaseModel):
    """病历查询参数（统一管理查询条件）"""
    patient_id: Optional[str] = Field(None, description="患者ID")
    patient_name: Optional[str] = Field(None, description="患者姓名（模糊查询）")
    stroke_location: Optional[str] = Field(None, description="卒中部位")
    paralysis_location: Optional[str] = Field(None, description="瘫痪部位")
    
    @field_validator('patient_id')
    @classmethod
    def convert_patient_id(cls, v):
        """将患者ID转换为整数"""
        if v is None:
            return None
        try:
            return int(v)
        except ValueError:
            return None
    
    class Config:
        json_schema_extra = {
            "example": {
                "patient_id": "1",
                "patient_name": "张三",
                "stroke_location": "左侧大脑中动脉供血区",
                "paralysis_location": "右侧肢体"
            }
        }


# ========== 分页查询参数 ==========
class PaginationParams(BaseModel):
    """分页参数"""
    page: int = Field(1, ge=1, description="页码")
    per_page: int = Field(10, ge=1, le=100, description="每页数量")
    
    @property
    def skip(self) -> int:
        """计算 skip 值"""
        return (self.page - 1) * self.per_page


# ========== 分页响应 ==========
class PaginatedMedicalRecordsResponse(BaseModel):
    """病历分页响应（标准化分页数据结构）"""
    medical_records: List[dict] = Field(..., description="病历列表")
    total: int = Field(..., description="总记录数")
    total_pages: int = Field(..., description="总页数")
    current_page: int = Field(..., description="当前页码")
    per_page: int = Field(..., description="每页数量")
    
    @classmethod
    def create(
        cls, 
        records: List[dict], 
        total: int, 
        page: int, 
        per_page: int
    ) -> "PaginatedMedicalRecordsResponse":
        """创建分页响应"""
        total_pages = (total + per_page - 1) // per_page if per_page > 0 else 0
        return cls(
            medical_records=records,
            total=total,
            total_pages=total_pages,
            current_page=page,
            per_page=per_page
        )


# ========== 批量操作 ==========
class MedicalRecordBatchExportRequest(BaseModel):
    """批量导出病历请求"""
    record_ids: List[str] = Field(..., min_length=1, description="病历ID列表")
    
    @field_validator('record_ids')
    @classmethod
    def validate_record_ids(cls, v):
        """验证并转换病历ID"""
        if not v:
            raise ValueError("record_ids不能为空")
        
        # 转换为整数列表
        try:
            return [int(rid) for rid in v]
        except ValueError:
            raise ValueError("record_ids必须是有效的数字列表")
    
    class Config:
        json_schema_extra = {
            "example": {
                "record_ids": ["1", "2", "3"]
            }
        }

